﻿using System;
using System.Configuration;
using System.Linq;
using SDCloudSolution.SDCloud.BusinessLayer.Interfaces;
using SDCloudSolution.SDCloud.DataLayer.Interfaces;
using SDCloudSolution.SDCloud.DataLayer.MongoDb.Interfaces;
using SDCloudSolution.SDCloud.ModelRunAgent.Infrastructure.Engines;

namespace SDCloudSolution.SDCloud.ModelRunAgent.Infrastructure
{
    public class ApplicationSettingsProvider : 
        IFileStorageSettingsProvider, 
        IIdentityDbConnectionStringProvider, 
        ISdCloudMongoDbSettingsProvider,
        IPysdServiceSettingsProvider
    {
        public string FileStorageBasePath => ConfigurationManager.AppSettings["FileStorageBasePath"];

        public string IdentityDbConnectionString => "DefaultConnection";

        public string ModelResultMongoStorageConnectionString => ConfigurationManager.AppSettings["MongoDbConnectionString"];

        public string ModelResultDataBaseName => ConfigurationManager.AppSettings["MongoDbDataBaseName"];

        public string PythonServiceUrl => TryGetStringValue("PyServiceUrl");

        public int PythonServiceTimeout => TryGetIntValue("PyServiceTimeOut");

        public int[] PythonServicePorts => TryGetIntArray("PyServicePortNumbers");

        public string PythonExecutionPath => TryGetStringValue("PythonPath");

        public string PythonExecutionArguments => TryGetStringValue("PysdArguments");

        private static int ConvertStringToInt(string value)
        {
            int result;
            return string.IsNullOrEmpty(value) || !int.TryParse(value, out result)
                ? 0
                : result;
        }

        public static int TryGetIntValue(string property)
        {
            return ConvertStringToInt(TryGetStringValue(property));
        }


        public static int[] TryGetIntArray(string property)
        {
            return TryGetStringArray(property)
                .Select(ConvertStringToInt)
                .ToArray();
        }

        public static string[] TryGetStringArray(string property)
        {
            return string.IsNullOrEmpty(TryGetStringValue(property))
                ? new string[] { }
                : TryGetStringValue(property).Split(',');
        }

        public static string TryGetStringValue(string property)
        {
            try
            {
                return ConfigurationManager.AppSettings[property];
            }
            catch (Exception)
            {
                return string.Empty;
            }
        }
    }
}
